package cn.schoolwow.util.module.query.queryPackage.flow;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.module.query.queryPackage.domain.QueryPackageOption;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Stack;

public class FilterClassListFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        List<Class> classList = flowContext.getData("classList", List.class);
        QueryPackageOption queryPackageOption = flowContext.checkInstanceData(QueryPackageOption.class);

        if(queryPackageOption.queryClassNameList.isEmpty()){
            return;
        }
        //排除查询类自身
        classList.removeIf(aClass -> {
            return queryPackageOption.queryClassNameList.contains(aClass.getName());
        });

        classList.removeIf(aClass -> {
            Set<String> interfaceNameSet = new HashSet<>();

            Stack<Class> interfacesStack = new Stack<>();
            interfacesStack.push(aClass);
            while(!interfacesStack.isEmpty()){
                Class clazz = interfacesStack.pop();
                interfaceNameSet.add(clazz.getName());
                Class[] interfaces = clazz.getInterfaces();
                if(interfaces.length>0){
                    for(Class classInterface:interfaces){
                        interfacesStack.push(classInterface);
                    }
                }
            }

            boolean shouldRemove = true;
            for(String interfaceName:interfaceNameSet){
                if(queryPackageOption.queryClassNameList.contains(interfaceName)){
                    shouldRemove = false;
                    break;
                }
            }
            return shouldRemove;
        });
    }

    @Override
    public String name() {
        return "过滤类列表";
    }

}
